//
//  CodeViewController.swift
//  GhostWorld
//
//  Created by Kam on 2018/7/26.
//  Copyright © 2018 LKGood. All rights reserved.
//

import UIKit
import PKHUD

class CodeViewController: BaseViewController {
  
  // MARK: - IBOutlets
  
  @IBOutlet private weak var codeTextField: UITextField!
  
  
  // MARK: - Private vars
  
  
  
  // MARK: - Private methods
  
  
  
  // MARK: - Public vars
  
  
  
  // MARK: - Lifecycle
  
  override func viewDidLoad() {
    super.viewDidLoad()
    
    // Do any additional setup after loading the view.
  }
  
  override func viewDidAppear(_ animated: Bool) {
    super.viewDidAppear(animated)
    
    codeTextField.becomeFirstResponder()
  }
  
  override func didReceiveMemoryWarning() {
    super.didReceiveMemoryWarning()
    // Dispose of any resources that can be recreated.
  }
  
  // MARK: - IBActions
  
  @IBAction func consumeCode(_ sender: Any) {
    guard let code = codeTextField.text, code.trim().count > 0 else {
      HUD.flash(.labeledError(title: "鬼符码不能为空", subtitle: "请重试"), delay: 1.5)
      codeTextField.becomeFirstResponder()
      return
    }
    
    HUD.show(.labeledProgress(title: "兑换中", subtitle: "请稍后..."))
    let body = ["code": code.trim()]
    API.shared.requestAPI (
      APIURLStrings.codeConsume,
      method: .post,
      body: body,
      header: API.shared.memeberHeader,
      successCallback: { json in
        
      let albumName = json["album_name"].stringValue
      HUD.flash(.labeledSuccess(title: albumName, subtitle: "已兑换"), delay: 2)
      NotificationCenter.default.post(name: .reloadPurchasedHistory, object: nil)
      self.navigationController?.popViewController(animated: true)
    }) { (message, code) in
      if code == 1000 {
        HUD.hide()
        let alert = UIAlertController(title: message, message: nil, cancelTitle: "知道了", cancelHandler: nil)
        self.present(alert, animated: true)
      } else {
        HUD.flash(.labeledError(title: message, subtitle: "请重试"), delay: 1.5)
      }
    }
  }
  
  // MARK: - Public methods
  
  
}

extension CodeViewController: UITextFieldDelegate {
  func textFieldShouldReturn(_ textField: UITextField) -> Bool {
    view.endEditing(true)
    return true
  }
}
